
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using SharpArch.Core.DomainModel;

namespace Peak.Core
{
  public class User : Entity
  {
    public virtual string UserName { get; set; }
    public virtual string Password { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Email { get; set; }
    public virtual Project DefaultProject { get; set; }
    public virtual IList<Role> Roles { get; protected set; }
    public virtual string Comment { get; set; }
    public virtual DateTime LastActivityDate { get; set; }
    public virtual DateTime LastLoginDate { get; set; }
    public virtual DateTime LastPasswordChangedDate { get; set; }
    public virtual DateTime CreationDate { get; set; }
    public virtual bool IsOnLine { get; set; }
    public virtual bool IsLockedOut { get; set; }
    public virtual DateTime LastLockedOutDate { get; set; }    
    public virtual Profile Profile { get; set; }

    public User()
    {
      Roles = new List<Role>();
      Profile = new Profile();
    }    

    public virtual void AddRole(Role role)
    {
      role.UsersInRole.Add(this);
      Roles.Add(role);
    }

    public virtual void RemoveRole(Role role)
    {
      role.UsersInRole.Remove(this);
      Roles.Remove(role);
    }

    public virtual void SetPassword(string password)
    {
      Password = EncodePassword(password);
    }

    public static string EncodePassword(string password)
    {
      if (password == null)
        return null;
      HashAlgorithm algorithm = HashAlgorithm.Create();

      byte[] data = algorithm.ComputeHash(Encoding.ASCII.GetBytes(password));

      string result = "";
      foreach (byte b in data)
        result += b.ToString("X2");
      return result;
    }
  }  
}